﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using popLib;
using PhotoMgr.src.common;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Data.Objects;
using PhotoMgr.src.gui.photo;

namespace PhotoMgr.src.database
{
    public partial class DBManager
    {
        public static ReturnSet Save_Image(bool isUpdateMode, Image updatedItem, Image originalItem)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                using (var transaction = entity.BeginTransaction())
                {
                    try
                    {
                        //save Images first============================================
                        entity.Images.Attach(updatedItem);

                        if (isUpdateMode)
                        {
                            entity.ApplyOriginalValues("Image", originalItem);
                        }
                        else
                        {
                            entity.ObjectStateManager.ChangeObjectState(updatedItem, EntityState.Added);
                        }
                        entity.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);

                        //update Path============================================                        
                        if (Path.GetDirectoryName(updatedItem.ImagePath).ToUpper() != Configuration.Instance.PhotoPath)
                        {
                            string imagePath = Path.Combine(Configuration.Instance.PhotoPath, DateTime.Now.ToString("yyyy-MM") );
                            if (!Directory.Exists(imagePath)) Directory.CreateDirectory(imagePath); 
                            string imageFile = Path.Combine(imagePath, string.Format("{0}-{1}-{2}{3}", updatedItem.ImageID, updatedItem.ArtistID, updatedItem.ImageTitle, Path.GetExtension(updatedItem.ImagePath)));
                            
                            int counter = 0;
                            while (File.Exists(imagePath))
                            {
                                imageFile = Path.Combine(imagePath, string.Format("{0}-{1}-{2}{3}", updatedItem.ImageID, updatedItem.ArtistID, updatedItem.ImageTitle + counter++, Path.GetExtension(updatedItem.ImagePath)));
                            }

                            File.Copy(updatedItem.ImagePath, imageFile, false);

                            updatedItem.ImagePath = imageFile;

                            entity.SaveChanges();
                        }
                                                
                        //commit here============================================
                        transaction.Commit();

                        return new ReturnSet(true, updatedItem);
                    }
                    catch (OptimisticConcurrencyException ocex)
                    {
                        entity.Images.Detach(updatedItem);
                        transaction.Rollback();
                        Global.WriteLog(ocex, "Images.OptimisticConcurrencyException");
                        return new ReturnSet(false, Global.DBErrorType.RecordOutOfDate, ocex.Message);
                    }
                    catch (Exception ex)
                    {
                        entity.Images.Detach(updatedItem);
                        transaction.Rollback();
                        Global.WriteLog(ex, "Images.Exception");
                        Global.WriteLog(ex.InnerException, "Save_BH_Ngoai.Exception.InnerException");

                        if (ex.InnerException.Message.Contains("String or binary data would be truncated"))
                            return new ReturnSet(false, Global.DBErrorType.DataLengthTruncated, ex.Message);

                        return new ReturnSet(false, Global.DBErrorType.UnknownError, ex.Message);
                    }

                }
            }
        }

        public static void ImageScore_SaveScore(int roundImageID, int userID, double score, string status, ScoreType scoretype)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                ImageScore item;
                var rs = entity.ImageScores.Where(x => x.RoundImageID == roundImageID && x.UserID == userID);
                if (rs.Count() > 0)
                {
                    item = rs.First();
                    
                    if (scoretype == ScoreType.MainScore ) item.Score = score;
                    if (scoretype == ScoreType.SubScore) item.SubScore = score;
                    if (scoretype == ScoreType.ThirdScore) item.ThirdScore = score;

                    item.Status = status;
                }
                else
                {
                    item = new ImageScore();
                    item.DateCreated = Global.GetServerDateTime();

                    if (scoretype == ScoreType.MainScore) item.Score = score;
                    if (scoretype == ScoreType.SubScore) item.SubScore = score;
                    if (scoretype == ScoreType.ThirdScore) item.ThirdScore = score;

                    item.Status = status;
                    item.UserID = userID;
                    item.RoundImageID = roundImageID;
                    entity.ImageScores.AddObject(item);
                }
                
                entity.SaveChanges();
            }
        }

        public static List<ImageScore> ImageScore_ViewScore(int roundImageID)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.ImageScores.Where(x => x.RoundImageID == roundImageID).ToList();
            }
        }

        public static List<View_RoundImage> RoundImage_ListByRoundID(int roundID)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.View_RoundImage.Where(x => x.RoundID == roundID).ToList();
            }
        }

        //public static List<View_RoundImage> Round_ListImage(int roundID)
        //{
        //    using (var entity = new PhotoMgrEntities(GenConnectionString()))
        //    {
        //        return entity.Round_ListImage(roundID).ToList();
        //    }
        //}

        //public static List<View_ContestUserSetting> Contest_GetContestUserSetting(int contestID)
        //{
        //    using (var entity = new PhotoMgrEntities(GenConnectionString()))
        //    {
        //        return entity.View_ContestUserSetting.Where(x => x.ContestID == contestID).ToList();
        //    }
        //}

        public static List<RoundImage> SearchRoundImage(int round_id)
        {
            var entity = new PhotoMgrEntities(GenConnectionString());
            
            return entity.RoundImages.Where(x => x.RoundID == round_id).ToList<RoundImage>();
        }

        public static database.Image Detail_Image(int image_id)
        {
            var entity = new PhotoMgrEntities(GenConnectionString());

            return entity.Images.Where(x => x.ImageID == image_id).First();
        }
    }
}
